<?php
/* $Id$ */

/**
 * Autorensystem project.php (c) Copyright 2008 Enrico Homann
 */

define (IN_PROJECT_PHP, "true");

require_once "lib/application/BaseApplication.class.php";

require_once "lib/container/ContainerProcessor.class.php";

require_once "lib/storage/File.class.php";
require_once "lib/security/Security.class.php";

require_once "application/logic/ProjectDatabase.class.php";

require_once "application/configurations/Profile.class.php";
require_once "application/logic/db/ProjectSQL.class.php";


/*
 * Known Bugs:
 *
 * (18. Aug 08)		Datenbank download	Bei Datengroessen kleiner 1 KByte scheint es dann und wann
 *						zu vorzeitigem loeschen der erzeugten Temporaerdatei zu kommen 
 *
 */
 


class Project extends BaseApplication {

	private $author_roles_list		= null;

	private $author_list_html		= null;
	private $author_details_html		= null;

	private $projects_as_option_list_html		= null;
	private $author_roles_as_option_list_html	= null;


	/* Einige vordefinierte Klasseninterne Templates */

	private $tpl_projects_as_option_list_html	= "<option>{project_id} {project_name}</option>";
	private $tpl_author_roles_as_option_list_html	= "<option>{author_role_id} {author_role_name}</option>";
	
	private $tpl_author_avatar_html		= "<img src=\"{author_avatar_file}\" title=\"Avatar von {author_name}\" width=\"100px\" height=\"100px\" />";


	/* Vordefinierte Keywords und deren Callback Funktionen */

	private $keywords_table_details_by_id_html_arr  = null;

	/* Temporaere Dateien Liste */

	private	$createdTemporaryFiles_array		= null;

	/* SiteMap */

	private $siteMap_templatePages = array ( 
						"index" => array (

							/* Format: Vorherige Seite als Trigger, Beschreibung, Templateseite */
							array( 	null, "Blabla", "template-pages/tpl-pages/index.tpl", "http://link" ),
							array( "edit_membership", "", "" )
						
						)
					);

	private $siteMap_construct     = array(
						"index"  => array(
								array(
									"menupunkt1",
									"submenu" => array(
										"1.1",
										"1.2",
										"submenu"	=> null
									)
								),
								array(
									"menupunkt1"
								),
								array(
									"menupunkt1"
								)
							)

					);
				

	private	$whoami_currentAuthorID				= null;
		 
	/* Tabellen */

	private $database_tables_array 				= array(
		"articles", "authors", "authors_roles", "categories", "container_contents", "container_filters",
		"database_security", "memberships", "messages", "projects", "sessions", "uploads"
	);


	/**
	 * Konstruktor
         **
         * @param $currentAuthorID Die AutorenID des eingeloggten Benutzers
	 *			( 0 = globaler admin (developmodus) )
	 */

	function Project( $currentAuthorID ) {

		/* Superklasse aufrufen */
		$this->BaseApplication ( 
			get_class(), 
			"5.0", 
			"PHP Version muss groesser als 5.0 sein",
			array( "standard", "session" )
		);

		/* Login Daten sichern */
		$this->whoami_currentAuthorID = $currentAuthorID;

		/* Neues Sitzungsprofil */
		$this->setProfile_class ( new Profile() );
		
		$this->setMySQLConnection_class( new ProjectDatabase( $this, $this->getProfile_class()->getSQLConfig() ) );

		if ( !$this->getMySQLConnection_class()->connect() ) {
				die ("Serververbindung fehlgeschlagen!");
		}

		//echo "registeredSessionID".$_SESSION["registeredSessionID"];

		/* Startet eine neue Session, sofern noch nicht vorhanden */
		if ( !isset($_SESSION["registered_session_id"]) && (session_id() == "") ) {
			session_start();

			$_SESSION["registered_session_id"] = true;

			/* Datenbank eintrag */
			$this->sql_add_row_table_sessions( $this->whoami_currentAuthorID,
				session_id()				
			);
		}


		/* Session Variablen evtl initialisieren */
		if ( !isset( $_SESSION["current_number_of_uploads"] ) ) {
			$_SESSION["current_number_of_uploads"] = 0;			
		}

		if ( !isset( $_SESSION["createdTemporaryFiles_array"] ) ) {
			$_SESSION["createdTemporaryFiles_array"] == null;

			$this->removeTemporaryFileDirectoryBySessionID( session_id() );

		} else {
			$this->updateSession( session_id() );
		}

		if ( !file_exists( $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( session_id() ) ) )
			mkdir( $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( session_id() ) );
	

		/** Datenbankbereinigungen **/
		
		/* Statischer zeitlicher Verzeichnis Cleanup */
		if ( $this->getProfile_class()->getScriptConfig()->getTempDirectoryTimeoutForCleanUp() != null )
			$this->processTemporaryFilesByExpiredSessionID();


		/** Nachrichten **/

		/* Status Message auf Initialisiert setzten */
		$this->setStatusMessage("Project wurde instanziiert", false);

		/* Error Message auf Fehlerfrei setzen */
		$this->setErrorMessage("Alles l&auml;uft einwandfrei", true);

		
	}

	/**
	 * Destruktor automatisch ab PHP 5 
	 */

	function __destruct() {
		$this->cleanExit();
	}

	/**
         * Beendet das Skript sauber
         */

	function cleanExit() {

		/* Loesche Temporaere Dateien x Sekunden nach dem registrieren */
		//$this->removeTemporaryFiles();

	}


	function getDB_class() {
		return $this->db_class;
	}

	
	function set_keywords( $tpl_processor_class ) {

	}

	function registerTemporaryFile( $fileName ) {
		$_SESSION["createdTemporaryFiles_array"][$fileName] = array(
									"filename" => $fileName,
									"timestamp" => time()
								);
	}

	function removeTemporaryFiles() {
		if ( $_SESSION["createdTemporaryFiles_array"] == null ) return;

		foreach( $_SESSION["createdTemporaryFiles_array"] as $key=>$value ) {

			$currentTime = time();

			//echo "timestamp=".($currentTime-$value["timestamp"]);

			$dirFilename = $value["filename"];

			if ( file_exists ($dirFilename) ) { 


			
				$dirFilesize = @filesize( $dirFilename );

				$afterSeconds = $dirFilesize / $this->getProfile_class()->getScriptConfig()->
					getTempFilesMinimumDownloadSpeedInBytesPerSeconds();

				/* Zeitbonus aufschlagen */
				$afterSeconds = $afterSeconds *  $this->getProfile_class()->getScriptConfig()->getTempFilesTimeBonusNumerical();

				//echo "<p>AfterSec ".$afterSeconds."</p>";

				if ( (strlen($dirFilename) > 1) && ( ($currentTime-$value["timestamp"]) >= $afterSeconds ) ) {
				
					//echo "Loesche: ".$dirFilename;

					/* Aus Hash loeschen */
					unset( $_SESSION["createdTemporaryFiles_array"][$key] );
				
					/* Von der Platte loeschen */
					if ( file_exists( $dirFilename ) ) {
						@unlink( $dirFilename );
					} 
						else echo $dirFilename." existiert nicht?!";

				}

			} else {
				/* Datei existiert nicht mehr */
				/* Aus Hash loeschen */
				unset( $_SESSION["createdTemporaryFiles_array"][$key] );

			}
		}
	}

	function removeTemporaryFileDirectoryBySessionID( $sessionID ) {

		if ( file_exists( $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( $sessionID ) ) ) {

			//rmdir( $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( $sessionID ) );
			File::regenerateDirectory( $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( $sessionID )  );


		}

	}

	function processTemporaryFilesByExpiredSessionID() {
		
		if ( $this->getMySQLConnection_class()->processRow(
			"SELECT * FROM ". 
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"sessions".
			" WHERE ".
				"`session_has_expired` = 0", 
			"expired_sessions" ) === false ) {

			$this->setErrorMessage("Fehler beim ermitteln der ausgelaufenen Sessions !", true);

		}

	}

	function updateSession ( $session_id ) {
		$this->sql_update_session_activity_by_id( $session_id );
	}

	function query_human( $query, $failureMsg, $successMsg ) {

		if ( $this->getMySQLConnection_class()->query( $query ) === false) {

			$this->setErrorMessage($failureMsg.": ".mysql_error(), true);
			return false;
		} else
			$this->setStatusMessage($successMsg, false);		

	}


	function db_new_project_row() {


	}

	/** Keywords **/

	function get_keyword_posted( $trigger ) {
		return $_REQUEST[$trigger];
	}


	function getTableAsList_html( $table, $registeredCallback ) {

		$processReturn =  $this->getMySQLConnection_class()->processRowToConcatedElements(
					"SELECT * FROM ".
						$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
						$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
						$table, 

					$registeredCallback 
				);
		

		if ( $processReturn === false ) {
			$this->setErrorMessage("(getTableAsList_html) Fehler beim Zeilenabruf! ".mysql_error());
		}

		return $processReturn;

	}

	function getTableAsRowDetails_html( $table, $registeredCallback, $idTrigger, $id ) {

		if ( $id == "" ) return false;

		$processReturn = $this->getMySQLConnection_class()->processUniqueRow(
				"SELECT * FROM ". 
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					$table.
				" WHERE `".$idTrigger."`= ".$id, $registeredCallback 
			);

		if ( $processReturn === false ) {

			$this->setErrorMessage("(getTableAsRowDetails) Fehler beim Zeilenabruf! ".mysql_error(), true);

		}

		return $processReturn;

	}

	function getAuthorsRolesList() {
		/* TODO */
		return $this->author_roles_list;
	}

	function getAuthorsList_html() {
		return $this->getTableAsList_html( "authors", "author_list_html" );
	}

	function get_keyword_author_details( $id ) {
		return $this->getTableAsRowDetails_html( "authors", "author_details_html", "author_id", $id );
	}

	function getAuthorsRolesAsOptionList_html() {

		if ( $this->getMySQLConnection_class()->processRow(
				"SELECT * FROM ". 
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					"authors_roles", "author_roles_as_optionlist" 
			) === false ) {

			$this->setErrorMessage("Fehler beim ermitteln der Autoren Rollen !", true);

		}

		return $this->author_roles_as_option_list_html;
	}



	function getProjectAsOptionList_html() {
		return $this->getTableAsList_html( "projects", "projects_as_optionlist" );
	}

	function getProjectsList_html() {
		return $this->getTableAsList_html( "projects", "project_list_html" );
	}

	function get_keyword_project_details( $id ) {
		return $this->getTableAsRowDetails_html( "projects", "project_details_html", "project_id", $id );
	}

	
	/** SQL **/

	function sql_process_keyword_author_memberships ( $query_obj ) {

		$membershipString = "";

		$q = $this->getMySQLConnection_class()->query(
				"SELECT * FROM ". 
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					"memberships".
				" WHERE `membership_author_id`=".$query_obj->author_id);

		$membership_counter = 1;
		if ( $q !== false ) {
			while ( $membership_obj = mysql_fetch_object($q) ) {

				//echo $membership_obj->membership_project_id;

				$project_obj = $this->getMySQLConnection_class()->getQueryObject( 
					"SELECT * FROM ". 
						$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
						$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
						"projects".
					" WHERE `project_id`=".$membership_obj->membership_project_id, 
				"Konnte Project ID nicht ermitteln" );

				$membershipString .= (($membershipString !== "") ? ",": "").
					"<a href=\"\" title=\"Rolle ".$this->sql_get_obj_from_table_author_role_by_id($membership_obj->membership_author_role_id)->author_role_name.
					"\">".$project_obj->project_name."</a>";


				if ( ($membership_counter > 0) && ($membership_counter % 3) == 0 ) $membershipString .= "<br />";

				$membership_counter++;

			}
		} else die ("Fehler beim Mitgliedschaften ermitteln! ".mysql_error() );

		/* Falls keine Mitgliedschaft gefunden, entsprechend vermerken */
		if ($membershipString == "") 
			$membershipString = "&lt;keine&gt;";

		$this->getTemplateProcessor_class()->registerKeyword("{author_memberships}", $membershipString);

	}

	function sql_process_keyword_author_uploads ( $query_obj ) {

		$uploadsString = "";

		$q = 	$this->getMySQLConnection_class()->query(
				"SELECT * FROM ".
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					"uploads".
				" WHERE `upload_author_id`=".$query_obj->author_id
			);

		$uploads_counter = 1;
		if ( $q !== false ) {
			while ( $uploads_obj = mysql_fetch_object( $q ) ) {

				//echo $uploads_obj->upload_id;

				$content_obj = $this->getMySQLConnection_class()->getQueryObject( 
							"SELECT * FROM ". 
								$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
								$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
								"container_contents".
							" WHERE `content_upload_id`=".$uploads_obj->upload_id, 
							"Konnte Upload ID in content nicht ermitteln" 
						);

				$uploadsString .= 	"".
								"#".
								$content_obj->content_id." ( ".
								$content_obj->content_filename. " ) ".
							"<br />"
				;

				if ( ($uploads_counter > 0) && ($uploads_counter % 11) == 0 ) $uploadsString .= "<br />";

				$uploads_counter++;

			}
		} else die ("Fehler beim Uploads ermitteln! ". mysql_error() );

		/* Falls keine Mitgliedschaft gefunden, entsprechend vermerken */
		if ($uploadsString == "") 
			$uploadsString = "&lt;keine&gt;";

		$this->getTemplateProcessor_class()->registerKeyword("{author_uploads}", $uploadsString);

	}

	function sql_helper_keyword_avatar ( $query_obj ) {

		$found = false; $avatar_container_content_id = 0;
		$tablename = null;
		foreach( $query_obj as $key=>$value ) {
			if ( ($i = strpos( $key, "_avatar_container_content_id")) !== false ) {
				$found = true;
				$avatar_container_content_id = $value;
				$tablename = substr( $key, 0, $i );
				break;
			}
		}
		if ( !$found ) return false;

		if ( $avatar_container_content_id > 0 ) {

			echo "TableName: ".$tablename;

			$container_content_obj = $this->sql_get_obj_from_table_container_contents_by_id (
						$avatar_container_content_id
			);

			$tempName = $this->saveUploadTemporaryOnDisk( $avatar_container_content_id );

			$this->getTemplateProcessor_class()->registerKeyword( 
				"{".$tablename."_avatar_file}", $tempName);

			$this->getTemplateProcessor_class()->registerKeyword(
				"{".$tablename."_avatar}",
				$this->getTemplateProcessor_class()->processString( $this->tpl_author_avatar_html )
			);

		} else {
			$this->getTemplateProcessor_class()->registerKeyword(
				"{".$tablename."_avatar_file}", "" ); 
			$this->getTemplateProcessor_class()->registerKeyword(
				"{".$tablename."_avatar}",	"" );
		}


	}

	function sql_process_keyword_author_avatar ( $query_obj ) {

		return $this->sql_helper_keyword_avatar( $query_obj );
/*
		$found = false; $avatar_container_content_id = 0;
		foreach( $query_obj as $key=>$value ) {
			if ( preg_match( "/_avatar_container_content_id/", $key ) ) {
				$found = true;
				$avatar_container_content_id = $value;
				break;
			}
		}
		if ( !$found ) return false;

		if ( $avatar_container_content_id > 0 ) {

			$container_content_obj = $this->sql_get_obj_from_table_container_contents_by_id (
						$avatar_container_content_id
			);

			$tempName = $this->saveUploadTemporaryOnDisk( $avatar_container_content_id );

			$this->getTemplateProcessor_class()->registerKeyword("{author_avatar_file}", $tempName);



			$this->getTemplateProcessor_class()->registerKeyword("{author_avatar}", 
			$this->getTemplateProcessor_class()->processString( $this->tpl_author_avatar_html )
			);

		} else {
			$this->getTemplateProcessor_class()->registerKeyword("{author_avatar}", "" ); 
			$this->getTemplateProcessor_class()->registerKeyword("{author_avatar_file}", "" );
		}
*/
	}

	function sql_process_author_list_html_callback( $query_obj ) {

		/* Details Keywords setzen */
		$this->sql_process_author_details_html_callback( $query_obj );
	
		/* Keywords in Elemententemplate ersetzen */
		return $this->getTemplateProcessor_class()->processPage("application/webpages/tpl/authors.list.element.tpl.xhtml.php");
	}

	function sql_process_author_details_html_callback( $query_obj ) {

		/** Keywords einfacher Datensaetze setzen **/ 

		$this->getTemplateProcessor_class()->registerKeywordsFromSlashStrippedObject( $query_obj );

		/** Avatar des Autoren **/

		$this->sql_process_keyword_author_avatar ( $query_obj );

		/** Mitgliedschaften des Autoren **/

		$this->sql_process_keyword_author_memberships ( $query_obj );

		/** Uploads des Authoren **/

		$this->sql_process_keyword_author_uploads ( $query_obj );

		/** Autoren Details Template Page behandeln **/

		return $this->getTemplateProcessor_class()->processPage("application/webpages/tpl/authors.details.tpl.xhtml.php");
	}

	function sql_process_author_roles_as_option_list_callback( $query_obj ) {

		$this->author_roles_as_option_list_html .= $this->getTemplateProcessor_class()->processObjectTemplates( 
			$query_obj, $this->tpl_author_roles_as_option_list_html );

		//$this->author_roles_as_option_list_html .= "<option>".$query_obj->author_role_id." ".$query_obj->author_role_name."</option>";
	}

	function sql_process_author_roles_as_list_of_objects_callback( $query_obj ) {
		$this->author_roles_list[ $query_obj->author_role_id ] = $query_obj;
	}


	function sql_process_project_as_option_list_callback( $query_obj ) {

		return $this->getTemplateProcessor_class()->processObjectTemplates( 
			$query_obj, $this->tpl_projects_as_option_list_html 
		);

	}

	function sql_process_project_details_html_callback( $query_obj ) {

		/** Keywords einfacher Datensaetze setzen **/ 

		$this->getTemplateProcessor_class()->registerKeywordsFromObject( $query_obj );

		/** Avatar des Autoren **/

//		$this->sql_process_keyword_author_avatar ( $query_obj );

		/** Mitgliedschaften des Autoren **/

//		$this->sql_process_keyword_author_memberships ( $query_obj );

		/** Uploads des Authoren **/

//		$this->sql_process_keyword_author_uploads ( $query_obj );

		/** Projekt Details Template Page behandeln **/

		return $this->getTemplateProcessor_class()->processPage("application/webpages/tpl/projects.details.tpl.xhtml.php");
	}


	function sql_process_project_list_html_callback( $query_obj ) {

		/* Details Keywords setzen */
		$this->sql_process_project_details_html_callback( $query_obj );
	
		/* Keywords in Elemententemplate ersetzen */
		return $this->getTemplateProcessor_class()->processPage("application/webpages/tpl/projects.list.element.tpl.xhtml.php");
	}



	function sql_process_sessions_for_expired_once ( $query_obj ) {

		/** Expired Check **/

		//echo "lastact: ".$query_obj->session_last_activity_unix_timestamp;

		if ( (time()-$query_obj->session_start_unix_timestamp) >= 
			$this->getProfile_class()->getScriptConfig()-> getTempDirectoryTimeoutForCleanUp() ) {

			/** Sofern Expired, Expired Flag setzen **/

			$q =	"UPDATE ".
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					"sessions".
		     		" SET `session_has_expired` = 1".
		     		" WHERE ".
					"`session_id`=".$query_obj->session_id;

			$this->query_human( $q, "Fehler beim Session aussortieren", "Session-Aussortierung erfolgreich beendet." );			

			/** Sofern Expired, Temporaeres Verzeichnis loeschen **/

			//echo "Loesche ".$query_obj->session_sessionid;

			$this->removeTemporaryFileDirectoryBySessionID ( $query_obj->session_sessionid );

		}
		

	}

	/** SQL GETTER SEKTION **/

	function sql_get_obj_from_table_by_id ( $table, $idTrigger, $idNumber, $failureMsg ) {

		return $this->getMySQLConnection_class()->getQueryObject(
				"SELECT * FROM ". 
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
					$table.
				" WHERE `".$idTrigger."`=".$idNumber,
			$failureMsg
		);
	}
	

	function sql_get_obj_from_table_author_role_by_id( $idNumber ) {

		return $this->sql_get_obj_from_table_by_id ( 
				"author_roles", 					/* $table */
				"author_role_id", 					/* $idTrigger */
				$idNumber, 						/* $idNumber */
				"Konnte die Autoren-Rollen ID nicht ermitteln"		/* $failureMsg */
		);

	}

	function sql_get_obj_from_table_author_by_id ( $idNumber ) {

		return $this->sql_get_obj_from_table_by_id ( 
				"authors", 						/* $table */
				"author_id", 						/* $idTrigger */
				$idNumber, 						/* $idNumber */
				"Konnte die Autoren ID nicht ermitteln"			/* $failureMsg */
		);

	}

	function sql_get_obj_from_table_container_contents_by_id ( $idNumber ) {

		return $this->sql_get_obj_from_table_by_id ( 
				"container_contents", 					/* $table */
				"content_id", 						/* $idTrigger */
				$idNumber, 						/* $idNumber */
				"Konnte die Content ID nicht ermitteln"			/* $failureMsg */
		);

	}

	/** SQL ADD SEKTION **/

	function sql_add_row_table_memberships( $project_id, $author_id, $author_role ) {

		$q = 	"INSERT INTO ". 
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"memberships".
			" (`membership_project_id`, `membership_author_id`, `membership_author_role_id`, `membership_active`)".
			" VALUES (".
				$project_id.", ".$author_id.", ".$author_role.", 1".
			")";

		//echo $q;

		if ( $this->getMySQLConnection_class()->query( $q ) === false) {

			$this->setErrorMessage("Fehler beim eintragen einer Mitgliedschaft", true);
			return false;
		} else
			$this->setStatusMessage("Mitgliedschaft eingetragen", false);
			

		return true;

	}

	function sql_add_row_table_sessions( $author_id ) {
		
		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"sessions".
				" ( `session_sessionid`, `session_ipv4`, `session_author_id`, `session_start_unix_timestamp`, `session_http_referer`, `session_http_user-agent` )".
			" VALUES".
				" ( ".
				" '".	addslashes( session_id() ).			"',".
				" '".	addslashes( $_SERVER['REMOTE_ADDR'] ).	"',".
				" '".	$author_id.			"',".
				" '".	time().				"',".
				" '".	addslashes( $_SERVER['HTTP_REFERER'] ).	"',".
				" '".	addslashes( $_SERVER['HTTP_USER_AGENT'] ).	"'".
				" )";

		//echo $q;

		if ( $this->getMySQLConnection_class()->query( $q ) === false) {
			die ( "<p>".mysql_error()."</p>" );
		};

		return mysql_insert_id();
	}

	function sql_add_row_defaults_table( $table, $base_values_arr ) {

		/* Keys */ 
		$keyvalue = $this->getMySQLConnection_class()->getFlattenedTrustedHTMLValueHashArray_SQL_key_value(
			$base_values_arr
		);

		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				$table.
			" SET ".$keyvalue;

		$this->query_human( $q, "Fehler beim einfuegen eines Autoren", "Einfuegen eines Autoren erfolgreich beendet." );

		/* Die Autoren ID des neuen Eintrags zurueck liefern */
		return mysql_insert_id();



	}

	function sql_add_row_defaults_table_authors() {

/*		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
				" ( `author_currently_active` ) ".
			" VALUES".
				" ( 1 )";

		$this->query_human( $q, "Fehler beim einfuegen eines Autoren", "Einfuegen eines Autoren erfolgreich beendet." );
*/
		/* Die Autoren ID des neuen Eintrags zurueck liefern */
//		return mysql_insert_id();

		return $this->sql_add_row_defaults_table( "authors", array( "author_currently_active" => 1 ) );

	} 

	function sql_add_row_defaults_table_projects() {

		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"projects".
				" ( `project_currently_active` ) ".
			" VALUES".
				" ( 1 )";

		$this->query_human( $q, "Fehler beim einfuegen eines Autoren", "Einfuegen eines Autoren erfolgreich beendet." );

		/* Die Autoren ID des neuen Eintrags zurueck liefern */
		return mysql_insert_id();
	} 


	/** SQL DELETE SEKTION **/

	function sql_del_row_table_memberships( $membership_id ) {

		$q = 	"DELETE FROM ". 
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"memberships".
			" WHERE `membership_id`=$membership_id";

		//echo $q;

		if ( $this->getMySQLConnection_class()->query( $q ) === false) {

			$this->setErrorMessage("Fehler beim l&ouml;schen einer Mitgliedschaft", true);
			return false;
		} else
			$this->setStatusMessage("Mitgliedschaft gel&ouml;scht", false);
			

		return true;

	}

	function sql_check_memberships_this_row_exists( $project_id, $author_id, $author_role_id) {

		$q = 	"SELECT * FROM ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"memberships".
			" WHERE ".
				"`membership_project_id`=$project_id AND `membership_author_id`=$author_id AND `membership_author_role_id`=$author_role_id";

		return ( $this->getMySQLConnection_class()->getQueryObject( $q, "Bereits vorhanden" ) );

	}

	//function sql_update_


	function sql_change_authors_account_details_by_id( $author_id, $author_name, 
		$author_email ) {

		$obj_arr = array( 	"author_name" 	=> $author_name,
					"author_email"	=> $author_email
				);

		return $this->getMySQLConnection_class()->
				sql_change_table_row_by_id( "authors", "author_id", $author_id, $obj_arr );

	}

	function sql_change_project_details_by_id( $project_id, $project_name, 
		$project_description_short ) {
		
		$obj_arr = array( 	"project_name" 			=> $project_name,
					"project_description_short"	=> $project_description_short
				);

		return $this->getMySQLConnection_class()->
				sql_change_table_row_by_id( "projects", "project_id", $project_id, $obj_arr );

	}

	function sql_change_all_post_details_by_id ( $id, $table ) {

		/** Ermittle alle moeglichen Keys in der Tabelle **/

		
		/** Vergleiche diese Keys ob evtl in _REQUEST Objekt gesetzt ** /


		/** Trage Werte von gesetzten Werten ein **/



	}

	function sql_del_table_row_by_id( $table, $triggerId, $id ) {

		$q = 	"DELETE FROM ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				$table.
			" WHERE `".$triggerId."`=".$id;
		
		$queryResHead = $this->getMySQLConnection_class()->query( $q );

		if ($queryResHead === false) 
			$this->setErrorMessage( "Fehler!: ".mysql_error(), true );

		return $queryResHead;

	}

	function sql_del_authors_account_by_id( $author_id ) {

		/* Kopfdaten entfernen */
	
		$queryResHead = $this->sql_del_table_row_by_id( "authors", "author_id", $author_id );


		/* Mitgliedschaften  */

		if ( !$this->getProfile_class()->getScriptConfig()->shallDatabaseKeepMembershipEntriesFromDeletedAccounts ) {
			/* Auch Memberships loeschen */
			$this->sql_del_table_row_by_id( "memberships", "membership_author_id", $author_id );
		}

	}

	function sql_update_session_activity_by_id ( $session_id ) {

		$q =	"UPDATE ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"sessions".
			" SET `session_last_activity_unix_timestamp` = '".time()."'".
			" WHERE ".
				"`session_id`=".$session_id;

		$this->query_human( $q, "Fehler beim Session updaten", "Session-Update erfolgreich beendet." );	

	} 


	function db_get_tables_list() {
		return $this->database_tables_array;
	}

	function sql_reset_tables() {

		foreach( $this->db_get_tables_list() as $value ) {
			$q =	"DELETE FROM ".
					$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
					$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				$value;

			$this->query_human( $q, "Fehler beim Session updaten", "Session-Update erfolgreich beendet." );	
		}

	}

	function getTemporaryPrefix( $content_obj ) {

		$temporaryPrefixForFileTicket = "";
		$temporaryPrefixForFileTicket = hash( "sha256",
			session_id()./*$content_obj->datablock*/
			$this->getProfile_class()->getSecurityConfig()->getTempFilesMagicKeyword().
			/*mt_rand(0, time()).*/
			$content_obj->content_id
			/*$_SESSION["current_number_of_resurrected_uploads"]*/
		);

		$temporaryPrefixForFileTicket = str_replace("/", "_", $temporaryPrefixForFileTicket);
		$temporaryPrefixForFileTicket = str_replace(".", "_", $temporaryPrefixForFileTicket);

		return $temporaryPrefixForFileTicket;

	}

	function saveUploadTemporaryOnDisk( $content_id ) {
		
		$_SESSION["current_number_of_resurrected_uploads"]++;

		$container_content_obj = $this->sql_get_obj_from_table_container_contents_by_id (
						$content_id
		);

		if ( $container_content_obj !== false ) {

			$fileChecker_class	= new FileChecker( null );

			//echo "<p>".$this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( session_id() )."</p>";

			$tempFileName	= $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( session_id() ).
					  $this->getTemporaryPrefix( $container_content_obj ).
					  $fileChecker_class->getExtensionByMimeType( $container_content_obj->content_mimetype ); 

			//while ( file_exists( $tempFileName ) ) {
				/* Anderen Namen generieren */
				$tempFileName	= $this->getProfile_class()->getScriptConfig()->getTempFilesDirectory( session_id() ).
					  $this->getTemporaryPrefix( $container_content_obj ).
					  $fileChecker_class->getExtensionByMimeType( $container_content_obj->content_mimetype ); 
			//}

			$this->registerTemporaryFile( 
				dirname( $_SERVER["SCRIPT_FILENAME"] )."/".
				$tempFileName
			);
			
			//echo dirname( $_SERVER["SCRIPT_FILENAME"] )."/".
			//	$tempFileName;

			$fd = fopen( $tempFileName, "w" );
			fwrite ($fd, $container_content_obj->content_datablock );
			fclose ($fd);

			/* Nur relativen Pfad zurueck liefern */
			return $tempFileName;

		} else
			return false;

	}

	function saveUploadInDatabase( $author_id, $fileUpload_class, $container_types_array ) {

		/* Multithread und -Session sicheres speichern */

		$_SESSION["current_number_of_uploads"]++;

		$current_session_number_of_uploads = $_SESSION["current_number_of_uploads"];
		$key_timestamp = time();

		//echo "upload ticket: ". session_id()."#".$current_session_number_of_uploads."#".$key_timestamp; 

		/** Status Meldung **/
		$this->setStatusMessage("Speichere Daten ... ", false );		

		/** Datenverwertung **/ 

		$container_class 	= new ContainerProcessor( $fileUpload_class->getFileContent() );
		$processed_content 	= $container_class->processData( $container_types_array );
		$fingerprint_content 	= Security::getFingerprint_sh256( $processed_content,
			$this->getProfile_class()->getSecurityConfig()->getTempFilesMagicKeyword()
		); 


		/** Datenbank Eintraege **/

		/* Container Tabellennamen aus der Art des Contents ermitteln */

		$container_typenames = "";
		foreach ( $container_types_array as $value ) {
			$container_typenames .= " ".$value;
		}

		$container_typenames = trim( $container_typenames );

		/* Anzahl der Upload des Autoren um eins erhoehen */

		$q =	"UPDATE ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
		     	" SET `author_number_of_uploads`=author_number_of_uploads+1".
		     	" WHERE ".
				"`author_id`=".$author_id;

		$this->query_human( $q, "Fehler beim Upload", "Upload erfolgreich beendet." );


		/* Damit eine neue Upload Zeile erzeugen */

		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"uploads".
		      		" (upload_author_upload_number, upload_author_id)".
		      	" SELECT ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
				".".
		      		"author_number_of_uploads".
				",".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
				".".
		      		"author_id".
			" FROM ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
		      	" WHERE ".
				"`author_id`=".$author_id;


		$this->query_human( $q, "Fehler beim Upload", "Upload erfolgreich beendet." );

		/* Restliches der Zeile in Tabelle updates Updaten */
	
		$q =	"UPDATE ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"uploads".
		     	" SET".
				" `upload_author_sessionid` = '".session_id()."'".
				", `upload_tmpname` = '".addslashes( $fileUpload_class->getCurrentSavedFileTemporaryAbsFilename() )."'".
				", `upload_unixtimestamp` = '".$key_timestamp."'".
				", `upload_author_session_upload_number` = '".$current_session_number_of_uploads."'".
				", `upload_filesize_was` = '".$fileUpload_class->getCurrentFileSize()."'".
		     	" WHERE".
				" `upload_id`=LAST_INSERT_ID()";

		$this->query_human( $q, "Fehler beim Upload", "Upload erfolgreich beendet." );


		/* Damit eine neue Upload Zeile erzeugen */

		$q = 	"INSERT INTO ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"container_contents".
		      		" ( content_datablock, content_upload_id, content_size, content_mimetype, content_filename, content_filtertypes, content_fingerprint_sha256 )".
		      	" VALUES (".
					"'".addslashes( $processed_content )."'".
					", LAST_INSERT_ID() ".
					", '".strlen( $processed_content )."'".
					", '".addslashes( $fileUpload_class->getCurrentFileMimeType() )."'".
					", '".addslashes( $fileUpload_class->getCurrentPostedFileName() )."'".
					", '".addslashes( $container_typenames )."'".
					", '".addslashes( $fingerprint_content )."'".
				")";

		$this->query_human( $q, "Fehler beim Upload", "Upload erfolgreich beendet." );

		/* content_id zurueck liefern */
		return mysql_insert_id();
	}

	function saveUploadedAvatarInDatabase( $author_id, $fileUpload_class, $container_types_array ) {

		$content_id = $this->saveUploadInDatabase( $author_id, $fileUpload_class, $container_types_array );

		if ( $content_id == 0 ) die ("Fehler beim ermitteln der content_id des Avatars ! ".mysql_error() );

		/* Den letzten Eintrag als Avatar in Autoren Details eintragen */

		$q =	"UPDATE ".
				$this->getProfile_class()->getSQLConfig()->getDatabaseName().".".
				$this->getProfile_class()->getSQLConfig()->getTablesPrefix().
				"authors".
		     	" SET `author_avatar_container_content_id`= '".$content_id."'".
		     	" WHERE ".
				"`author_id`=".$author_id;

		$this->query_human( $q, "Fehler beim Upload", "Avatar erfolgreich eingetragen." );
		

	}

	function test() {

		//echo $this->profile->getScriptConfig()->getScriptDescription();
		echo "<p>Test</p>";



	}



}

	


?>